import json
import random
import traceback
from flask import request, make_response, g, send_from_directory
from pydantic import ValidationError
from werkzeug.exceptions import HTTPException
from config.const import constant, error_code
from database.db_manager import get_session
from forword.custom_error.request_errors import RequestError
from utils.log import log_api
from forword.custom_error.token_errors import TokenExpireError
from forword.custom_error.data_errors import DataChangedError

CONTENT_TYPE_JSON = 'application/json'
CODE_HTTP_SUCCESS = 200
NO_TEXT = '消息文本未配置'


def set_hook(app):

    @app.before_request
    def before_request():
        if request.method != "OPTIONS":
            log_api.info("获取上传参数")


    @app.errorhandler(RequestError)
    def handle_exception(e):
        # now you're handling non-HTTP exceptions only
        resp = ({"msg": str(e), "error_code": random.randint(10000,20000)})
        db_session = get_session()
        db_session.rollback()
        db_session.close()
        log_api.error(resp)
        return resp


    @app.errorhandler(Exception)
    def handle_exception(e):
        # now you're handling non-HTTP exceptions only
        resp = ({"msg": str(e), "error_code": random.randint(80000,90000)})
        db_session = get_session()
        db_session.rollback()
        db_session.close()
        log_api.error(resp)
        return resp

    @app.after_request
    def after_request(resp):
        db_session = get_session()
        db_session.close()
        resp.get_json()
        return resp

    @app.route('/api/v1/images/<path:filename>')
    def get_image(filename):
        return send_from_directory('static', filename)